"use strict";

import Vue from 'vue';
import axios from "axios";
import router from '../router';
import store from '../store';
import basepath from '../plugins/base.js';

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
//axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: basepath.apiurl//process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

//请求拦截器
_axios.interceptors.request.use(
  config => {
    //console.log('config: ', config);
    // Do something before request is sent

    //在 请求headers 中放入 Token
    if (store.state.user != null && store.state.user.Token.length > 0)
      config.headers.Authorization = store.state.user.Token;
    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor 响应拦截器
_axios.interceptors.response.use(
  response => {
    // Do something with response data
    if (response.status == 200)
      return response.data;
    else
      console.log(response);
  },
  error => {
    console.log('error: ', error);
    // Do something with response error
    console.log('error.response: ', error.response);
    let errstatus = error.response.status;

    switch (errstatus) {
      case 401:
        router.push({ path: '/login' })
        break;
    }
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin)

export default Plugin;
